<template>
  <div class="chat-container">
    <div class="chat-list" v-loading="loading">
      <div class="search-content">
        <el-input
          class="search-content__input"
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="keyword"
          clearable
          size="small"
          @input="onKeywordChange"
        />
      </div>
      <ul class="user-list">
        <li
          v-for="user in imuserList"
          :key="'user-' + user.memberId"
          @click="onUserClick(user)"
          :class="{
            'is-active': activeUser && activeUser.memberId == user.memberId
          }"
        >
          <el-avatar fit="cover" shape="square" :src="user.avatar" />
          <div class="nickname">
            {{ user.realname }}
          </div>
        </li>
      </ul>
    </div>
    <div class="chat-box" v-if="activeUser">
      <!-- <div>
        {{ activeUser }}
      </div> -->
      <div class="chat-box__content" ref="msgBox">
        <ul class="msg-list">
          <li
            :class="isMe(msg) ? 'me' : 'other'"
            v-for="msg in currentchat"
            :key="msg.id"
          >
            <!-- <p class="time">
                    <span>18:56</span>
                </p>-->
            <el-avatar
              fit="cover"
              shape="square"
              :src="isMe ? require('@/assets/logo.png') : activeUser.avatar"
            />
            <p v-html="msg.data" class="msg-content"></p>
          </li>
        </ul>
      </div>
      <div class="chat-box__input">
        <div class="tool-bar">
          <el-popover
            placement="top-start"
            width="296"
            trigger="click"
            v-model="faceVisible"
            popper-class="face-popover"
          >
            <ul class="face-list">
              <li
                v-for="item in 35"
                :key="'face-' + item"
                @click="onSelectFace(item)"
              >
                <el-image
                  :src="require(`@/assets/face/ee_${item}.png`)"
                  fit="cover"
                />
              </li>
            </ul>
            <a href="javascript:;" slot="reference" class="face" />
          </el-popover>
          <a href="javascript:;" class="file" @click="openFileClick">
            <input
              type="file"
              ref="file"
              accept="image/png,image/gif,image/jpeg"
              @change="onFileChange"
            />
          </a>
        </div>
        <div
          class="content-editable"
          ref="contentEditable"
          @input="onContentChange"
          contentEditable
          @keyup="onSendKey($event)"
        ></div>
        <div class="action">
          ctrl+enter 发送消息
          <el-button size="small" @click="onSend">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import request from "../utils/request";
import WebIM from "easemob-websdk";
import chat from "@/mixins/chat.js";

export default {
  mixins: [chat],
  data() {
    return {
      keyword: "",
      faceVisible: false,
      msgList: [],
      currentchat: [],
      html: "",
      imuserList: [],
      timer: null,
      page: 1,
      loading: false,
      activeUser: null,
      currentUser: {}
    };
  },
  async mounted() {
    const { webim_user, webim_pwd } = WebIM.utils.getCookie();
    const user = JSON.parse(webim_user);
    try {
      const res = await this.login(user.username, webim_pwd);
      this.currentUser = res;
      this.init();
      this.getImuserList();
    } catch (e) {
      console.log(e);
    }
    console.log(this.$imConn);
  },
  methods: {
    init() {
      this.$imConn.listen({
        onOpened: msg => {
          console.log("连接成功回调", msg);
          //连接成功回调
          // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
          // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
          // 则无需调用conn.setPresence();
        },
        onClosed: msg => {
          console.log("连接关闭回调", msg);
        }, //连接关闭回调
        onTextMessage: function(msg) {
          console.log(msg);
          if (msg.type == "groupchat") {
            this.messages.push(msg);
            // if (that.group.groupid == msg.to) {
            //   that.currentchat.push(msg);
            // }
            // debugger
            // this.$nextTick(() => {
            //   that.scrollToBottom();
            // });
          }
        }, //收到文本消息
        onEmojiMessage: msg => {
          console.log(msg);
        }, //收到表情消息
        onPictureMessage: msg => {
          console.log(msg);
        }, //收到图片消息
        onCmdMessage: msg => {
          console.log(msg);
        }, //收到命令消息
        onAudioMessage: msg => {
          console.log(msg);
        }, //收到音频消息
        onLocationMessage: msg => {
          console.log(msg);
        }, //收到位置消息
        onFileMessage: msg => {
          console.log(msg);
        }, //收到文件消息
        onVideoMessage: msg => {
          console.log(msg);
          // var node = document.getElementById("privateVideo");
          // var option = {
          //   url: message.url,
          //   headers: {
          //     Accept: "audio/mp4"
          //   },
          //   onFileDownloadComplete: function(response:any) {
          //     var objectURL = WebIM.utils.parseDownloadResponse.call(
          //       conn,
          //       response
          //     );
          //     node.src = objectURL;
          //   },
          //   onFileDownloadError: function() {
          //     console.log("File down load error.");
          //   }
          // };
          // WebIM.utils.download.call(conn, option);
        }, //收到视频消息
        onPresence: msg => {
          console.log(msg);
        }, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
        onRoster: msg => {
          console.log(msg);
        }, //处理好友申请
        onInviteMessage: msg => {
          console.log(msg);
        }, //处理群组邀请
        onOnline: () => {}, //本机网络连接成功
        onOffline: () => {
          alert("掉线了");
        }, //本机网络掉线
        onError: msg => {
          console.log(msg);
        }, //失败回调
        onBlacklistUpdate: list => {
          //黑名单变动
          // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
          console.log(list);
        },
        onReceivedMessage: msg => {
          console.log(msg);
        }, //收到消息送达服务器回执
        onDeliveredMessage: msg => {
          console.log(msg);
        }, //收到消息送达客户端回执
        onReadMessage: msg => {
          console.log(msg);
        }, //收到消息已读回执
        onCreateGroup: msg => {
          console.log(msg);
        }, //创建群组成功回执（需调用createGroupNew）
        onMutedMessage: msg => {
          console.log(msg);
        } //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
      });
    },

    async getImuserList() {
      try {
        this.loading = true;
        const { data } = await request.post(
          "/api/v1/member/imuser/list.shtml",
          { key: this.keyword, curPos: this.page }
        );
        this.page = data.pageInfo.curPos;
        this.imuserList = data.results || [];
      } catch (e) {
        console.log("error:", e);
      } finally {
        this.loading = false;
      }
    },
    isMe(msg) {
      return msg.from == this.currentUser.user.username;
    },
    onKeywordChange() {
      clearTimeout(this.timer);
      this.timer = setTimeout(this.getImuserList, 250);
    },
    onUserClick(user) {
      this.activeUser = user;
    },
    onSelectFace(idx) {
      console.log(idx);
      this.faceVisible = false;
      this.html += `<img src="@/assets/face/ee_${idx}.png"/>`;
    },
    openFileClick() {
      this.$refs.file.click();
    },
    onFileChange(ev) {
      const { files } = ev.target;
      console.log(files[0]);
    },
    onContentChange() {
      const el = this.$refs.contentEditable;
      const html = el.innerHTML;
      this.html = html;
    },
    onSendKey(e) {
      if (e.ctrlKey && e.keyCode == 13) {
        this.onSend();
      }
    },
    async onSend() {
      const el = this.$refs.contentEditable;
      try {
        const res = await this.sendPrivate(
          this.currentUser.memberId,
          this.html
        );
        this.msgList.push(res);
        if (this.currentUser.memberId == res.to) {
          this.currentchat.push(res);
        }
        el.innerHTML = "";
        this.html = "";
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } catch (err) {
        console.log(err);
      }
    },
    scrollToBottom() {
      const ele = this.$refs.msgBox;
      ele.scrollTop = ele.scrollHeight;
    }
  }
};
</script>
<style lang="less" scoped>
.chat-container {
  max-width: 1000px;
  min-width: 800px;
  margin: 0 auto;
  height: 80%;
  position: relative;
  display: flex;
  background-color: rgb(238, 238, 238);
  .chat-list {
    width: 280px;
    display: flex;
    flex-direction: column;
    height: 100%;
    float: left;
    background: rgb(46, 50, 56);
    .search-content {
      padding: 20px;
      &__input /deep/ input {
        background-color: #26292e;
        color: #fff;
        border: none;
      }
    }
    .user-list {
      flex: 1;
      overflow: auto;
      color: #fff;
      li {
        cursor: pointer;
        display: flex;
        align-items: center;
        padding: 4px 10px;
        margin-bottom: 8px;
        font-size: 14px;
        transition: all 0.25s ease-in-out;
        &:hover {
          background-color: rgba(0, 0, 0, 0.1);
        }
        &.is-active {
          background-color: rgba(0, 0, 0, 0.1);
        }
        .avatar {
          width: 40px;
          height: 40px;
          vertical-align: middle;
        }
        .nickname {
          flex: 1;
          padding-left: 10px;
        }
      }
    }
  }
  .chat-box {
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
    &__content {
      flex: 1;
      overflow: hidden;
      overflow-y: auto;
      .msg-list {
        li {
          display: flex;
          margin: 8px;
          margin-right: 0;
          .msg-content {
            flex: 1;
            margin: 0;
            padding: 10px;
          }
        }
      }
    }

    &__input {
      border-top: 1px solid rgb(214, 214, 214);
      padding: 16px;
      .tool-bar a {
        display: inline-block;
        width: 30px;
        height: 30px;
        &.face {
          background: url(~@/assets/icon.png) -404px -398px no-repeat;
        }
        &.file {
          background: url(~@/assets/icon.png) -120px -432px no-repeat;
          input {
            position: absolute;
            right: 0px;
            top: 0px;
            opacity: 0;
            z-index: -10;
          }
        }
      }
      .content-editable {
        height: 80px;
        overflow-x: hidden;
        overflow-y: auto;
        // padding: 4px;
        margin: 4px;
        font-size: 14px;
        box-sizing: content-box;
        outline: none;
      }
      .action {
        text-align: right;
        padding-top: 5px;
      }
    }
  }
}
.face-popover {
  .face-list {
    li {
      display: inline-block;
      margin: 0 6px 5px 0;
      cursor: pointer;
    }
  }
}
</style>
